from django.db.models.query import QuerySet
from rest_framework.fields import SerializerMethodField
from .models import Bug
from .models import Anchor
from user.models import User
from device.models import Device
from rest_framework import serializers
from user.serializers import UserSerializer


class UserField(serializers.RelatedField):

    def to_representation(self, value):
        user = {"id": value.id,
                "role": value.role,
                "realName": value.realName}
        return user

    def to_internal_value(self, data):
        return User.objects.get(id=data)


class UserListField(serializers.RelatedField):

    def to_representation(self, value):
        users = []
        if isinstance(value, int):
            users.append(self.queryset.get(id=value))
            return UserSerializer(users, many=True).data
        else:
            id_list = value.split(",")
            for u in id_list:
                users.append(self.queryset.get(id=u))
            return UserSerializer(users, many=True).data

    def to_internal_value(self, data):
        return data


class DeviceField(serializers.RelatedField):
    def to_representation(self, value):
        device = {"id": value.id,
                  "name": value.name,
                  "sn": value.sn,
                  "brand": value.brand,
                  "version": value.version,
                  "state": value.state}
        return device

    def to_internal_value(self, data):
        return Device.objects.get(id=data)


class BugeSrializer(serializers.ModelSerializer):

    handleUser = UserListField(queryset=User.objects.all())
    createUser = UserField(queryset=User.objects.all())
    device = DeviceField(queryset=Device.objects.all())
    createTime = SerializerMethodField()

    class Meta:
        model = Bug
        fields = '__all__'

    def get_createTime(self, obj):
        if(obj.createTime):
            return int(obj.createTime.timestamp())
        return None


class AnchorSrializer(serializers.ModelSerializer):
    device = DeviceField(queryset=Device.objects.all())
    createTime = serializers.SerializerMethodField()

    class Meta:
        model = Anchor
        fields = '__all__'

    def get_createTime(self, obj):
        if(obj.createTime):
            return int(obj.createTime.timestamp())
        return None
